from keras.models import load_model
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import recall_score
import pandas as pd

#加载模型
model = load_model('./model/data/model4_2_VGG 16_cats_vs_dogs_1.h5')
model.summary()

test_dir ='./train_dataset/train/test'
test_datagen=ImageDataGenerator(rescale=1./255)
test_generator=test_datagen.flow_from_directory(
    directory=test_dir,
    target_size=(150,150),
    class_mode='binary',
    batch_size=20
)

print(test_datagen)
print(test_generator)
#测试
y_pred = model.predict(test_generator)
print(y_pred.shape)
# result = [(int) ((y_pred[i][0] + 0.5) / 1.0) for i in range(len(y_pred))]   #转换为整数是为了和二分类中的正负例相对应
# result = np.asarray(result).astype('float32')
# print(y_pred)
# 将prediction转换成一个数组
result = []
for i in range(len(y_pred)):
    if y_pred[i][0]>0.5:
        p=1
    else:
        p=0
    result.append(p)
results = np.asarray(y_pred).astype('int32')

# result = (y_pred>0.5).astype("int32")
# print(result)
print(result)
print(test_generator.labels.shape)
print(np.shape(result))
test_label =test_generator.labels #标签
print(test_label.shape)

# pd.crosstab(test_label, result, rownames='labels', colnames='predicts')
# print(pd.crosstab(y_test, result,  colnames=['predict']))

#分类报告
from sklearn.metrics import classification_report
print("分类报告:\n",classification_report(test_label, result))
print("混淆矩阵:\n",confusion_matrix(test_label, result))
print("召回率：",recall_score(test_label,result))

#绘制混淆矩阵
predict = ["cat","dog"]
fact = ["cat","dog"]
classes = list(set(fact))
r1 = confusion_matrix(test_label, result)
plt.figure(figsize=(12,10))
confusion = r1
plt.imshow(confusion, cmap=plt.cm.Blues)
indices = range(len(confusion))
indices2 = range(3)
plt.xticks(indices,classes,rotation=40,fontsize=18)
plt.yticks([0.00,1.00],classes,fontsize=18)
plt.ylim(1.5,-0.5)  #设置y的纵坐标的上下限
plt.title("Confusion matrix",fontdict={'weight':'normal','size':18})
#设置color bar的标签大小
cb = plt.colorbar()
cb.ax.tick_params(labelsize=18)
plt.xlabel('Predict label',fontsize=18)
plt.ylabel('True label',fontsize=18)
print("len(confusion",len(confusion))
for first_index in range(len(confusion)):
    for second_index in range(len(confusion[first_index])):
        if confusion[first_index][second_index]>200:
            color='black'
        else:
            color="black"
        plt.text(first_index,second_index,confusion[first_index][second_index],fontsize=18,color=color,verticalalignment='center',horizontalalignment='center')
plt.show()